package com.haois.mp.database.module.offaccounts.service;

import com.haois.mp.database.module.common.daomain.UserToken;
import com.haois.mp.wechat.constants.Enum.MenuEnum;
import com.haois.mp.wechat.util.WxUtil;
import me.chanjar.weixin.common.exception.WxErrorException;
import com.haois.mp.wechat.common.BusinessRemind;
import com.haois.mp.database.commom.enums.MpTypeEnum;
import com.haois.mp.database.module.common.daomain.Driver;
import com.haois.mp.database.module.common.daomain.Peccancy;
import com.haois.mp.database.module.common.daomain.Vehicle;
import com.haois.mp.database.module.wxserver.util.TempMsgUtil;
import com.haois.mp.database.module.wxserver.util.VehicleUtil;
import com.haois.mp.database.module.common.service.IUserTokenService;
import com.haois.mp.database.util.jx.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * description
 *
 * @author RuiHaoZ on GuangZhou
 * @date 2018/10/1 0:23
 */
@Service
public class RemindVehicleService {

    private Logger logger = LoggerFactory.getLogger(RemindVehicleService.class);
    @Autowired
    private VehicleService vehicleService;
    @Autowired
    private IUserTokenService iUserTokenService;

    @Value("${defined.wxmp.base-url}")
    private String baseUrl;

    public void businessRemind(String memberNum, String[] tempDate, String url) {
        UserToken userToken = iUserTokenService.findByUserId(memberNum, MpTypeEnum.OFFACCOUNTS.getType());
        if (userToken != null) {
            try {
                BusinessRemind.remindByWx(tempDate,
                        userToken.getOpenId(), TempMsgUtil.title_Sys,
                        TempMsgUtil.temp_Sys, TempMsgUtil.temp_Sys_Color, url);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
    }

    public void businessRemind(String memberNum, String[] tempDate) {
        businessRemind(memberNum, tempDate, null);
    }

    /**
     * 更新违章记录
     *
     * @param isDirect 是否直连查询违章信息
     * @return
     */
    public int vehiclePeccancy(boolean isDirect) {
        AtomicInteger pushSize = new AtomicInteger();
        List<Vehicle> vehicles = vehicleService.findVehicle(null);
        vehicles.forEach(vehicle -> {
            int size = vehiclePeccancy(vehicle, isDirect);
            pushSize.addAndGet(size);
        });
        return pushSize.get();
    }

    /**
     * 推送对应车辆违章信息有变化的详情
     *
     * @param vehicle  车辆信息
     * @param isDirect 是否直连
     * @return
     */
    public int vehiclePeccancy(Vehicle vehicle, boolean isDirect) {
        AtomicInteger pushSize = new AtomicInteger();
        List<Peccancy> peccancyList = vehicleService.updateAndGetChangeWzInfo(vehicle.getPlate(), isDirect);
        int size = peccancyList.size();
        for (int i = 0; i < size; i++) {
            Peccancy peccancy = peccancyList.get(i);
            String[] tempDate = new String[]{
                    peccancy.getArchiveno(),
                    peccancy.getVehiclePlate() + "(" + String.valueOf(i + 1) + "/" + String.valueOf(size) + ")",
                    peccancy.getHandled().equals("1") ? "已处理" : "未处理",
                    String.valueOf(peccancy.getFen()),
                    String.valueOf(peccancy.getMoney()),
                    peccancy.getDate(),
                    peccancy.getWzcity(),
                    peccancy.getArea(),
                    peccancy.getAct()
            };
            List<String> memberNums = vehicleService.findVehicleMem(vehicle.getId());
            memberNums.forEach(memberNum -> {
                UserToken userToken = iUserTokenService.findByUserId(memberNum, MpTypeEnum.OFFACCOUNTS.getType());
                if (userToken != null) {
                    try {
                        BusinessRemind.remindByWx(tempDate, userToken.getOpenId(), TempMsgUtil.title_Remind_Pec,
                                TempMsgUtil.temp_Remind_Pec, TempMsgUtil.temp_Remind_Pec_Color, null);
                        pushSize.getAndIncrement();
                    } catch (WxErrorException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        return pushSize.get();
    }


    /**
     * 驾照信息提醒
     *
     * @param memberNum 用户号
     * @return
     */
    public int driverValidPeriod(String memberNum) {
        AtomicInteger pushSize = new AtomicInteger();
        logger.info("手动任务【更新驾驶证信息】手动触发");
        List<Driver> drivers = vehicleService.findDriver(memberNum);
        drivers.forEach(driver -> {
            pushSize.addAndGet(this.driverValidPeriod(driver, memberNum));
        });
        return pushSize.get();
    }

    /**
     * 驾照信息提醒
     *
     * @param driver    驾驶证信息
     * @param memberNum 用户编号
     * @return
     */
    public int driverValidPeriod(Driver driver, String memberNum) {
        AtomicInteger pushSize = new AtomicInteger();
        logger.info("手动任务【更新驾驶证信息】手动触发");
        StringBuffer content = new StringBuffer();
        content.append(VehicleUtil.getDriverInfo(driver));
        this.businessRemind(memberNum, new String[]{"驾照信息提醒" + "\n", content.toString(), "数据存在延迟，仅供参考"});
        pushSize.getAndIncrement();
        return pushSize.get();
    }

    /**
     * 根据用户编号获取车辆年检信息
     *
     * @param memberNum 用户编号
     * @return
     */
    public int vehicleValidPeriod(String memberNum) {
        AtomicInteger pushSize = new AtomicInteger();
        logger.info("手动任务【车辆年检信息】手动触发");
        List<Vehicle> vehicles = vehicleService.findVehicle(memberNum);
        vehicles.forEach(vehicle -> {
            int ps = this.vehicleValidPeriod(vehicle, memberNum);
            pushSize.addAndGet(ps);
        });
        return pushSize.get();
    }

    /**
     * 获取对应车辆信息
     *
     * @param vehicle   车辆
     * @param memberNum 用户号
     * @return
     */
    public int vehicleValidPeriod(Vehicle vehicle, String memberNum) {
        logger.info("手动任务【车辆年检信息】手动触发");
        AtomicInteger pushSize = new AtomicInteger();
        String url = MenuEnum.BTN_DRIVER_LINK.getUrl() + "?plate=" + vehicle.getPlate();
        url = WxUtil.transferWxUrl(url, MenuEnum.BTN_DRIVER_LINK.getKey(), baseUrl);

        Date nearTime = DateUtil.stringToDate(vehicle.getInspectTime(), DateUtil.yMd);
        int days = DateUtil.daysBetween(new Date(), nearTime);
        StringBuffer content = new StringBuffer();
        content.append(VehicleUtil.getVehicleInfo(vehicle, nearTime, days));
        this.businessRemind(memberNum, new String[]{"车辆信息提醒" + "\n", content.toString(), "数据存在延迟，仅供参考"}, url);
        pushSize.getAndIncrement();
        return pushSize.get();
    }


}
